package com.echo.util;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 响应工具类，用于设置JSON响应
 */
public class ResponseUtils {
    
    /**
     * 设置JSON响应
     * @param response HttpServletResponse对象
     */
    public static void setJsonResponse(HttpServletResponse response) {
        // 设置响应类型为JSON
        response.setContentType("application/json; charset=utf-8");
        response.setCharacterEncoding("UTF-8");
    }
    
    /**
     * 发送JSON数据到客户端
     * @param response HttpServletResponse对象
     * @param json JSON字符串
     * @throws IOException IO异常
     */
    public static void sendJson(HttpServletResponse response, String json) throws IOException {
        setJsonResponse(response);
        try (PrintWriter out = response.getWriter()) {
            out.print(json);
            out.flush();
        }
    }
    
    /**
     * 发送成功响应
     * @param response HttpServletResponse对象
     * @param message 成功消息
     * @throws IOException IO异常
     */
    public static void sendSuccessResponse(HttpServletResponse response, String message) throws IOException {
        String json = "{\"success\": true, \"message\": \"" + message + "\"}";
        sendJson(response, json);
    }
    
    /**
     * 发送错误响应
     * @param response HttpServletResponse对象
     * @param message 错误消息
     * @throws IOException IO异常
     */
    public static void sendErrorResponse(HttpServletResponse response, String message) throws IOException {
        String json = "{\"success\": false, \"message\": \"" + message + "\"}";
        sendJson(response, json);
    }
}